const express=require("express")
const bodyparser=require("body-parser")
const multiparty=require("multiparty")
const fse=require("fs-extra")
const fs=require("fs")
const path = require('path')
const app =express()
const UPLOAD_DIR=path.resolve(__dirname,"public/upload")
app.use(express.static(__dirname+"/public"))
app.use(bodyparser.urlencoded({extended:true}))

app.post("/upload",function(req,res){
  const form=new multiparty.Form({uploadDir:"template"})
  form.parse(req)
  form.on("file",async(name,chunk)=>{
    
    let chunkDir=`${UPLOAD_DIR}/${chunk.originalFilename.split(".")[0]}`
    if(!fse.existsSync(chunkDir)){
      await fse.mkdirs(chunkDir)
    }
    var dpath=path.join(chunkDir,chunk.originalFilename.split(".")[1])
    await fse.move(chunk.path,dpath,{overwrite:true})
    res.send("文件上传成功")
  })
  
})
app.get("/merge", async function (req,res){
  let name=req.query.name
  let fname=name.split(".")[0]
  let chunDir=path.join(UPLOAD_DIR,fname)
  let chunks=await fse.readdir(chunDir)
  let sortArr=chunks.sort((a,b)=>a-b)
  sortArr.map(chunkPath=>{
    fs.appendFileSync(
      path.join(UPLOAD_DIR,name),
      fs.readFileSync(`${chunDir}/${chunkPath}`)
    )
  })
  fse.removeSync(chunDir)
  res.send({msg:"合并成功",url:`http://localhost:3000/upload/${name}`})
})
app.listen("3000")
console.log("listen 3000")